package com.kamenrider.adventureaffiliated.procedures;

import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;

import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Entity;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;

@Mod.EventBusSubscriber
public class BosslifelimitdamageProcedure {

    // 预定义的生物伤害限制表（生物ID -> 最大伤害比例）
    private static final Map<String, Float> DAMAGE_LIMITS = new HashMap<>();
    static {
        // 限伤表
        DAMAGE_LIMITS.put("kamen_rider_boss_expand:qian_yun_yi", 0.2f);
        DAMAGE_LIMITS.put("kamen_rider_boss_expand:yu_zhi_yan", 0.001f);
        DAMAGE_LIMITS.put("kamen_rider_boss_expand:taoyao", 0.2f);
        DAMAGE_LIMITS.put("kamen_rider_boss_expand:youliya", 0.2f);
        DAMAGE_LIMITS.put("kamen_rider_boss_expand:thestarsarereversedforeverlost ", 0.2f);
    }

    @SubscribeEvent
    public static void onEntityAttacked(LivingAttackEvent event) {
        if (event != null && event.getEntity() != null) {
            execute(event, event.getEntity());
        }
    }

    @SubscribeEvent
    public static void onEntityHurt(LivingHurtEvent event) {
        if (event != null && event.getEntity() != null) {
            execute(event, event.getEntity());
        }
    }

    public static void execute(Entity entity) {
        execute(null, entity);
    }

    private static void execute(@Nullable Event event, Entity entity) {
        if (entity == null || !(entity instanceof LivingEntity)) {
            return;
        }

        String entityType = ForgeRegistries.ENTITIES.getKey(entity.getType()).toString();
        // 快速检查：如果不是我们要处理的生物，立即返回
        if (!DAMAGE_LIMITS.containsKey(entityType)) {
            return;
        }

        LivingEntity livingEntity = (LivingEntity) entity;
        float maxAllowedDamage = livingEntity.getMaxHealth() * DAMAGE_LIMITS.get(entityType);

        if (event instanceof LivingHurtEvent) {
            LivingHurtEvent hurtEvent = (LivingHurtEvent) event;
            float originalDamage = hurtEvent.getAmount();
            //判断初始伤害是否大于限伤值
            if (originalDamage > maxAllowedDamage) {
                // 将原始伤害替换为限制后的伤害
                hurtEvent.setAmount(maxAllowedDamage);
            }
        }
    }
}